import axios from 'axios';
import Toast from '../components/toast';
import Config from '../config';

const instance = axios.create({
  baseURL: '/api/isv/',
  withCredentials: true,
  timeout: 30000,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  validateStatus: () => true
});


// 错误处理拦截器
const checkError = res => {
  let {
    errorCode,
    success,
    errorMsg
  } = res.data;
  if (res.status === 200 && (success)) return res.data;

  if (errorMsg) errorMsg = errorMsg || '服务器开小差啦!';

  Toast(errorMsg);
  const httpError = new Error(errorMsg);
  httpError.code = errorCode || res.status;
  httpError.message = errorMsg;
  throw httpError;
};

instance.interceptors.response.use(checkError);


const http = {};
['get', 'post', 'put', 'delete', 'patch'].forEach((method) => {
  http[method] = (url, data, config = {}) => {
    const {
      token
    } = Config.dingtalk;
    const headers = {};

    if (token) {
      headers.Authorization = token;
    }

    return instance.request({
      url,
      method,
      data,
      params: method === 'get' ? data : {},
      ...config,
      headers: {
        ...headers,
        ...config.headers
      }
    });
  };
});

export default http;
